import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

# 生成数据
df = pd.read_excel('homework/the house data2.xlsx')  # 确保文件路径正确
X = df[["the house square","from house to subway station "]].values
y = df['the house price'].values
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1)

# 拆分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建不同degree的多项式回归模型
degrees = [1, 3, 5, 10]  # 可以根据需要调整degree
train_errors = []
test_errors = []

for degree in degrees:
    poly = PolynomialFeatures(degree)
    X_train_poly = poly.fit_transform(X_train)
    X_test_poly = poly.transform(X_test)
    
    model = LinearRegression()
    model.fit(X_train_poly, y_train)
    
    y_train_pred = model.predict(X_train_poly)
    y_test_pred = model.predict(X_test_poly)
    
    train_errors.append(mean_squared_error(y_train, y_train_pred))
    test_errors.append(mean_squared_error(y_test, y_test_pred))

# 绘制mse随degree变化的图像
plt.plot(degrees, train_errors, label='Training Error')
plt.plot(degrees, test_errors, label='Testing Error')
plt.scatter(degrees, train_errors, color='red')
plt.scatter(degrees, test_errors, color='blue')
plt.xlabel('Degree')
plt.ylabel('Mean Squared Error')
plt.legend()
plt.show()
